#include "graphics.opengl/pixelbuffer.h"

namespace dw
{
	namespace graphics
	{
		namespace opengl
		{

			PixelBuffer::PixelBuffer(const PixelFormat& pixelFormat, const uint32 width, const uint32 height, const Usage& usage) :
				IPixelBuffer(pixelFormat, width, height, usage)
			{
				int ipixelFormat			= 0;
				unsigned int numPixelFormat	= 0;


				HDC hdc = wglGetCurrentDC();

				int iAttributes[] = {
					WGL_SUPPORT_OPENGL_ARB,       GL_TRUE, 
					WGL_DRAW_TO_PBUFFER_ARB,      GL_TRUE,
					WGL_BIND_TO_TEXTURE_RGBA_ARB, GL_TRUE,
					WGL_PIXEL_TYPE_ARB,           WGL_TYPE_RGBA_ARB,
					WGL_ACCELERATION_ARB,         WGL_FULL_ACCELERATION_ARB,
		
					WGL_RED_BITS_ARB,             8,
					WGL_GREEN_BITS_ARB,           8,
					WGL_BLUE_BITS_ARB,            8,
					WGL_ALPHA_BITS_ARB,           8,

					WGL_DEPTH_BITS_ARB,           24,
					WGL_STENCIL_BITS_ARB,         0,
					WGL_DOUBLE_BUFFER_ARB,        GL_FALSE,
					0, 0 };
					
				int iFlags[] = { 
					WGL_PBUFFER_LARGEST_ARB,			GL_TRUE,
					WGL_TEXTURE_FORMAT_ARB,				WGL_TEXTURE_RGBA_ARB,
					WGL_TEXTURE_TARGET_ARB,				WGL_TEXTURE_2D_ARB,
					WGL_MIPMAP_TEXTURE_ARB,				GL_FALSE,
					0, 0 };
					
				if (!wglChoosePixelFormatARB(hdc, iAttributes, 0, 1, &ipixelFormat, &numPixelFormat))
					throw std::runtime_error(__FUNCTION__);
				_hpbuffer = wglCreatePbufferARB(hdc, ipixelFormat, _width, _height, iFlags);
				if (!_hpbuffer)
					throw std::runtime_error(__FUNCTION__);
				_hdc		= wglGetPbufferDCARB(_hpbuffer);
				_hglrc	= wglCreateContext(_hdc);				
			}

			PixelBuffer::~PixelBuffer()
			{
				wglDeleteContext(_hglrc);
				wglReleasePbufferDCARB(_hpbuffer, _hdc);
				wglDestroyPbufferARB(_hpbuffer);
			}

		} // namespace opengl
	} // namespace graphics
} // namespace dw